# -*- coding:utf-8 -*



'''
为验证码识别提供一个web查询接口
'''

import sys
sys.path.append("..")

import json
import os
from flask import Flask
from flask import request
from flask import render_template
import library.img_data as idata
import library.mlp as mlp



PYTHONIOENCODING='utf-8'

W1, b1, W2, b2 = mlp.startTrain()

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    return render_template('index.html')

@app.route('/search', methods=['GET'])
def signin_form():
    base64str = request.args.get('base64str')
    if base64str == None:
        resStr = json.dumps({"errorCode":1, "errorMessage":"缺少base64串参数"},
                            sort_keys=True, indent=4, separators=(',', ': ')).encode('utf-8').decode('unicode_escape')
        return resStr
    else:
        genFilePath = idata.base642img(base64str)
        dict = {}
        if genFilePath is None:
            dict['errorCode'] = 2
            dict['errorMessage'] = 'base64字符串错误，请使用url安全的base64串'
        else:
            res = mlp.vertifyInitimg(genFilePath, W1, b1, W2, b2)
            dict['errorCode'] = 0
            dict['res'] = res
        resStr = json.dumps(dict).encode('utf-8').decode('unicode_escape')
        return resStr

@app.route('/searchByPic', methods=['POST'])
def searchByPic():
    img = request.files['img']
    path = "../initimg/"
    if not os.path.exists(path):
        os.mkdir(path)
    file_path = path + img.filename
    img.save(file_path)
    res = mlp.vertifyInitimg(file_path, W1, b1, W2, b2)
    print(res)
    interface = request.form.get("interface", type=bool, default=False)
    if interface:
        return res
    return render_template('index.html', res = res)


if __name__ == '__main__':
    app.run(host='0.0.0.0')
